//
//  GWCategoriesViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/4/2.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import SnapKit

class GWCategoriesViewController: GWChildViewController {
    
    // MARK: - IBOutlets
    
    @IBOutlet private weak var seasonPanel: TitledPanel!
    @IBOutlet private weak var storyPanel: TitledPanel!
    @IBOutlet private weak var ylyPanel: TitledPanel!
    @IBOutlet private weak var zrjPanel: TitledPanel!
    @IBOutlet private weak var readerPanel: TitledPanel!
    @IBOutlet weak var gyccPanel: TitledPanel!
    
    // MARK: - Private vars
    
    private let seasonView: GWAlbumCoversView = .fromNib()
    private let storyView: GWAlbumCoversView = .fromNib()
    private let ylyView: GWAudiosView = .fromNib()
    private let zrjView: GWAudiosView = .fromNib()
    private let gyccView: GWAudiosView = .fromNib()
    private let readerView: GWReadersView = .fromNib()
    
    private var storyGroupIdentifier: Int = -1
    
    private var isFirstLoaded = true
    
    // MARK: - Private methods
    
    override func prepareUI() {
        
        // season panel
        seasonPanel.snp.makeConstraints { maker in
            maker.leading.equalTo(16)
            maker.trailing.equalTo(-16)
            maker.top.equalTo(70)
            maker.height.equalTo(GWAlbumCoversView.defaultHeight + 95)
        }
        seasonPanel.delegate = self
        seasonPanel.addSubview(seasonView)
        seasonView.snp.makeConstraints { maker in
            maker.top.equalTo(72)
            maker.leading.trailing.equalTo(0)
            maker.height.equalTo(GWAlbumCoversView.defaultHeight)
        }
        seasonView.delegate = self
        
        // story panel
        storyPanel.snp.makeConstraints { maker in
            maker.leading.equalTo(16)
            maker.trailing.equalTo(-16)
            maker.top.equalTo(seasonPanel.snp.bottom).offset(20)
            maker.height.equalTo(GWAlbumCoversView.defaultHeight + 95)
        }
        storyPanel.delegate = self
        storyPanel.addSubview(storyView)
        storyView.snp.makeConstraints { maker in
            maker.top.equalTo(72)
            maker.leading.trailing.equalTo(0)
            maker.height.equalTo(GWAlbumCoversView.defaultHeight)
        }
        storyView.delegate = self
        
        // 影留言 panel
        ylyPanel.snp.makeConstraints { maker in
            maker.leading.equalTo(16)
            maker.trailing.equalTo(-16)
            maker.top.equalTo(storyPanel.snp.bottom).offset(20)
            maker.height.equalTo(224)
        }
        ylyPanel.delegate = self
        ylyPanel.addSubview(ylyView)
        ylyView.snp.makeConstraints { maker in
            maker.top.equalTo(72)
            maker.leading.trailing.equalTo(0)
            maker.height.equalTo(GWAudiosView.defaultHeight)
        }
        
        // 在人间 panel
        zrjPanel.snp.makeConstraints { maker in
            maker.leading.equalTo(16)
            maker.trailing.equalTo(-16)
            maker.top.equalTo(ylyPanel.snp.bottom).offset(20)
            maker.height.equalTo(224)
        }
        zrjPanel.delegate = self
        zrjPanel.addSubview(zrjView)
        zrjView.snp.makeConstraints { maker in
            maker.top.equalTo(72)
            maker.leading.trailing.equalTo(0)
            maker.height.equalTo(GWAudiosView.defaultHeight)
        }
        
        //鬼影重重 panel
        gyccPanel.snp.makeConstraints { (maker) in
            maker.leading.equalTo(16)
            maker.trailing.equalTo(-16)
            maker.top.equalTo(zrjPanel.snp.bottom).offset(20)
            maker.height.equalTo(224)
        }
        gyccPanel.isHidden = true
        gyccPanel.delegate = self
        gyccPanel.addSubview(gyccView)
        gyccView.snp.makeConstraints { (maker) in
            maker.top.equalTo(72)
            maker.leading.trailing.equalTo(0)
            maker.height.equalTo(GWAudiosView.defaultHeight)
        }
        
        // reader panel
        readerPanel.snp.makeConstraints { maker in
            maker.top.equalTo(zrjPanel.snp.bottom).offset(20)
            maker.leading.equalTo(16)
            maker.trailing.equalTo(-16)
            maker.height.equalTo(192)
            //      maker.bottom.equalTo(view).offset(-30)
        }
        readerPanel.delegate = self
        readerPanel.addSubview(readerView)
        readerView.snp.makeConstraints { maker in
            maker.top.equalTo(72)
            maker.leading.equalTo(16)
            maker.trailing.equalTo(-16)
            maker.height.equalTo(GWReadersView.defaultHeight)
        }
        
        view.snp.makeConstraints { maker in
            maker.height.equalTo(1290)
        }
    }
    
    private func loadData() {
        API.shared.requestAPI(APIURLStrings.gwCategories, method: .get, successCallback: { json in
            
            // season
            if let seasonsJSON = json["latest_season_albums"].arrayObject as? [[String: Any]] {
                EntityManager.sync (
                    type: Album.self,
                    rawObject: seasonsJSON,
                    operations: [.update, .insert, .insertRelationships, .updateRelationships, .deleteRelationships],
                    completion: { error, albums in
                        
                        if error == nil {
                            self.seasonView.prepare(albums: albums!)
                        }
                })
            }
            
            // story
            if let storiesJSON = json["latest_story_albums"].arrayObject as? [[String: Any]] {
                EntityManager.sync (
                    type: Album.self,
                    rawObject: storiesJSON,
                    operations: [.update, .insert, .insertRelationships, .updateRelationships, .deleteRelationships],
                    completion: { error, albums in
                        
                        if error == nil {
                            self.storyGroupIdentifier = Int(albums!.first!.groupID)
                            self.storyView.prepare(albums: albums!)
                        }
                })
            }
            
            // yly
            if let ylyJSON = json["ying_liu_yan"].dictionaryObject {
                EntityManager.sync (
                    type: Album.self,
                    rawObject: [ylyJSON],
                    operations: [.update, .insert, .insertRelationships, .updateRelationships, .deleteRelationships],
                    completion: { error, albums in
                        
                        if error == nil {
                            if let audiosJSON = ylyJSON["audios"] as? [[String: Any]] {
                                
                                EntityManager.sync (
                                    type: Audio.self,
                                    rawObject: audiosJSON,
                                    operations: [.update, .insert],
                                    completion: { error, audios in
                                        if error == nil {
                                            self.ylyView.prepare(audios: audios!)
                                        }
                                })
                            }
                        }
                })
            }
            
            // zrj
            if let zrjJSON = json["zai_ren_jian"].dictionaryObject {
                EntityManager.sync (
                    type: Album.self,
                    rawObject: [zrjJSON],
                    operations: [.update, .insert, .insertRelationships, .updateRelationships, .deleteRelationships],
                    completion: { error, albums in
                        
                        if error == nil {
                            if let audiosJSON = zrjJSON["audios"] as? [[String: Any]] {
                                EntityManager.sync (
                                    type: Audio.self,
                                    rawObject: audiosJSON,
                                    operations: [.update, .insert],
                                    completion: { error, audios in
                                        
                                        if error == nil {
                                            self.zrjView.prepare(audios: audios!)
                                        }
                                })
                            }
                        }
                })
            }
            
            
            
            // reader
            if let readersJSON = json["readers"].arrayObject as? [[String: Any]] {
                EntityManager.sync (
                    type: Reader.self,
                    rawObject: readersJSON,
                    operations: [.insert, .update], completion: { error, readers in
                        if error == nil {
                            self.readerView.prepare(readers: readers!)
                        }
                })
            }
            
            UIView.animate(withDuration: 0.3) {
                self.seasonPanel.alpha = 1
                self.storyPanel.alpha = 1
                self.ylyPanel.alpha = 1
                self.zrjPanel.alpha = 1
                self.readerPanel.alpha = 1
            }
            
        }) { (message, code) in
            loggingPrint("[\(code)]: \(message)")
        }
        
        API.requsetPost(APIURLStrings.getAlbumLists, parameters: nil, success: { (JSON) in
            //gycc
            if let gyccJson = JSON["data"].dictionaryObject,gyccJson.count > 0 {
                self.gyccPanel.isHidden = false
                self.readerPanel.snp.updateConstraints { (maker) in
                    maker.top.equalTo(self.gyccPanel.snp.bottom).offset(20)
                }
                
                self.view.snp.updateConstraints { (maker) in
                    maker.height.equalTo(1290 + 224 + 20)
                }
                
                EntityManager.sync (
                    type: Album.self,
                    rawObject: [gyccJson],
                    operations: [.update, .insert, .insertRelationships, .updateRelationships, .deleteRelationships],
                    completion: { error, albums in
                        
                        if error == nil {
                            if let audiosJSON = gyccJson["audios"] as? [[String: Any]] {
                                EntityManager.sync (
                                    type: Audio.self,
                                    rawObject: audiosJSON,
                                    operations: [.update, .insert],
                                    completion: { error, audios in
                                        
                                        if error == nil {
                                            self.gyccView.prepare(audios: audios!)
                                        }
                                })
                            }
                        }
                })
            }
            
        }) { (Error) in
            
        }
        
    }
    
    // MARK: - Public vars
    
    
    
    // MARK: - Lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if isFirstLoaded {
            seasonPanel.alpha = 0
            storyPanel.alpha = 0
            ylyPanel.alpha = 0
            zrjPanel.alpha = 0
            readerPanel.alpha = 0
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        if isFirstLoaded {
            loadData()
            isFirstLoaded = false
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - IBActions
    
    
    
    // MARK: - Public methods
    
    
}

// MARK: - TitledPanelDelegate

extension GWCategoriesViewController: TitledPanelDelegate {
    
    func titledPanelButtonTapped(_ titledPanel: TitledPanel) {
        let storyboard = UIStoryboard(name: "ContentBrowsing", bundle: nil)
        
        switch titledPanel {
            
        case seasonPanel:
            let seasonsViewController = storyboard.instantiateViewController(withIdentifier: "SeasonsViewController") as! SeasonsViewController
            navigationController!.pushViewController(seasonsViewController, animated: true)
            
        case storyPanel:
            if storyGroupIdentifier > 0 {
                let simpleGroup = SimpleGroup(identifier: storyGroupIdentifier, name: "长篇剧场")
                let albumsViewController = storyboard.instantiateViewController(withIdentifier: "AlbumsViewController") as! AlbumsViewController
                albumsViewController.simpleGroup = simpleGroup
                navigationController!.pushViewController(albumsViewController, animated: true)
            }
            
        case ylyPanel:
            let albumDetailViewController = storyboard.instantiateViewController(withIdentifier: "AlbumDetailViewController") as! AlbumDetailViewController
            albumDetailViewController.albumIdentifier = Album.DefaultAlbumIdentifer.yingLiuYan.rawValue
            albumDetailViewController.canDisplayBasicInfo = false
            navigationController?.pushViewController(albumDetailViewController, animated: true)
            
        case zrjPanel:
            let albumDetailViewController = storyboard.instantiateViewController(withIdentifier: "AlbumDetailViewController") as! AlbumDetailViewController
            albumDetailViewController.albumIdentifier = Album.DefaultAlbumIdentifer.zaiRenJian.rawValue
            albumDetailViewController.canDisplayBasicInfo = false
            navigationController?.pushViewController(albumDetailViewController, animated: true)
            
        case gyccPanel:
            let albumDetailViewController = storyboard.instantiateViewController(withIdentifier: "AlbumDetailViewController") as! AlbumDetailViewController
            albumDetailViewController.albumIdentifier = Album.DefaultAlbumIdentifer.guiYinChongChong.rawValue
            albumDetailViewController.canDisplayBasicInfo = false
            navigationController?.pushViewController(albumDetailViewController, animated: true)
            
        case readerPanel:
            let readersViewController = storyboard.instantiateViewController(withIdentifier: "ReadersViewController") as! ReadersViewController
            navigationController!.pushViewController(readersViewController, animated: true)
            
        default:
            break
        }
    }
}

extension GWCategoriesViewController: GWAlbumCoversViewDelegate {
    func gwAlbumCoversView(_ view: GWAlbumCoversView, selectedWithAlbumIdentifier: Int) {
        let storyboard = UIStoryboard(name: "ContentBrowsing", bundle: nil)
        let albumDetailViewController = storyboard.instantiateViewController(withIdentifier: "AlbumDetailViewController") as! AlbumDetailViewController
        albumDetailViewController.albumIdentifier = selectedWithAlbumIdentifier
        navigationController?.pushViewController(albumDetailViewController, animated: true)  }
}
